﻿using System;
using System.Drawing;
using System.IO;
using System.Security.Permissions;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
using Microsoft.Win32;
using APIResult = System.Collections.Generic.List<System.Tuple<string, string>>;
using System.Text.RegularExpressions;
namespace FogOutlook {
	#if false

	public partial class BugReportForm : Form {
		MailItem mi = null;

		private ListViewItem lastItem = null;
		private PreviewForm previewForm = new PreviewForm();
		private static string NEW_TITLE = "Enter a title here...";

		private class ComboItem {
			public ComboItem(string text, string tag) { this.text = text; this.tag = tag; }
			public string text;
			public string tag;
			public override string ToString() { return text; }
		}

		public BugReportForm() {
			InitializeComponent();
			System.Drawing.Bitmap bmp = Properties.Resources.FogOutlook;
			this.Icon = System.Drawing.Icon.FromHandle(bmp.GetHicon());
			title.Text = NEW_TITLE;
		}

		public BugReportForm(MailItem mi) {
			InitializeComponent();
			System.Drawing.Bitmap bmp = Properties.Resources.FogOutlook;
			this.Icon = System.Drawing.Icon.FromHandle(bmp.GetHicon());
			this.mi = mi;
			columnHeader1.Width = -2;
		}

		private void BugReportForm_Load(object sender, EventArgs e) {
			FillDropDown(ThisAddIn.BugTracker.Projects, project);
			project.SelectedItem = Properties.Settings.Default.project;
			FillDropDown(ThisAddIn.BugTracker.Categories, category);
			category.Text = Properties.Settings.Default.category;
			FillDropDown(ThisAddIn.BugTracker.Priorities, priority);
			priority.Text = Properties.Settings.Default.priority;
			FillDropDown(ThisAddIn.BugTracker.People, assigned);
			assigned.Text = Properties.Settings.Default.assigned;
			FillDropDown(ThisAddIn.BugTracker.Areas, area);
			area.Text = Properties.Settings.Default.area;
			if(mi != null) {
				correspondent.Text = GetSenderSMTPAddress(mi);
				//bugreport.Text = Regex.Replace(mi.Body, "HYPERLINK \"(?<url>[^\"]*)\"(?<turl>.*)", "<a href='${url}'>${turl}</a>	");
				bugreport.Text = Regex.Replace(mi.Body, "HYPERLINK \"(mailto:)?(?<url>[^\"]*)\"(?<turl>.*)", "${url} ");

				//					string test = 
				//					Regex r = new Regex("HYPERLINK \".*\".*");
				//				string test = r.Replace(bugreport.Text, "<a href=$1:>$2:</a>");

				title.Text = mi.Subject;

				foreach(Attachment att in mi.Attachments) {
					string file = GetTempFilePathWithExtension(Path.GetExtension(att.FileName));
					att.SaveAsFile(file);
					ListViewItem lvi = listFiles.Items.Add(att.DisplayName);
					lvi.Tag = file;
					lvi.Checked = !Regex.IsMatch(att.FileName, "image[0-9]{3}.(png|jpg)"); // Try to exclude signature images by unchecking them, unfortunately they may be contained images instead :/
				}
				if(listFiles.Items.Count > 0)
					listFiles.Items[0].Selected = true;
			}
/*			FogBugzAPI fb = FogBugzAPI.Instance(false);
			if(fb != null) {
				while(fb.loaded != 100) { // Show progress dialog....or something
					System.Threading.Thread.Sleep(500);
				}
				FillDropDownWithResults(fb.project, project, "sProject", "ixProject");
				project.SelectedItem = Properties.Settings.Default.project;
				FillDropDownWithResults(fb.category, category, "sCategory", "ixCategory");
				category.Text = Properties.Settings.Default.category;
				FillDropDownWithResults(fb.priority, priority, "sPriority", "ixPriority");
				priority.Text = Properties.Settings.Default.priority;
				FillDropDownWithResults(fb.people, assigned, "sFullName", "ixPerson");
				assigned.Text = Properties.Settings.Default.assigned;
				if(mi != null) {
					correspondent.Text = GetSenderSMTPAddress(mi);
					//bugreport.Text = Regex.Replace(mi.Body, "HYPERLINK \"(?<url>[^\"]*)\"(?<turl>.*)", "<a href='${url}'>${turl}</a>	");
					bugreport.Text = Regex.Replace(mi.Body, "HYPERLINK \"(mailto:)?(?<url>[^\"]*)\"(?<turl>.*)", "${url} ");
			
//					string test = 
//					Regex r = new Regex("HYPERLINK \".*\".*");
	//				string test = r.Replace(bugreport.Text, "<a href=$1:>$2:</a>");
					
					title.Text = mi.Subject;
					
					foreach(Attachment att in mi.Attachments) {
						string file = GetTempFilePathWithExtension(Path.GetExtension(att.FileName));
						att.SaveAsFile(file);
						ListViewItem lvi = listFiles.Items.Add(att.DisplayName);
						lvi.Tag = file;
						lvi.Checked = !Regex.IsMatch(att.FileName, "image[0-9]{3}.(png|jpg)"); // Try to exclude signature images by unchecking them, unfortunately they may be contained images instead :/
					}
					if(listFiles.Items.Count > 0)
						listFiles.Items[0].Selected = true;
				}
			}*/
		}

		public string GetTempFilePathWithExtension(string extension) {
			var path = Path.GetTempPath();
			var fileName = Guid.NewGuid().ToString() + extension;
			return Path.Combine(path, fileName);
		}


		private void submit_Click(object sender, EventArgs e) {
			string[] files = new string[listFiles.CheckedItems.Count];
			int i=0;
			foreach(ListViewItem lvi in listFiles.CheckedItems)
				files[i++] = lvi.Tag.ToString();
//			listFiles.CheckedItems.CopyTo(files, 0);
			ThisAddIn.BugTracker.Submit(title.Text, bugreport.Text, project.SelectedItem.ToString(), category.SelectedItem.ToString(), priority.SelectedItem.ToString(),
				assigned.SelectedItem.ToString(), area.SelectedItem.ToString(), correspondent.Text, files);

			Properties.Settings.Default.Save();
/*			Dictionary<string, string> args = new Dictionary<string, string>();

			if(title.Text.Length > 0)
				args.Add("sTitle", title.Text);
			args.Add("sProject", getName(project.SelectedItem.ToString()));
			args.Add("sCategory", getName(category.SelectedItem.ToString()));
			args.Add("sPersonAssignedTo", getName(assigned.SelectedItem.ToString()));
			args.Add("sPriority", getName(priority.SelectedItem.ToString()));
			if(bugreport.Text.Length > 0)
				args.Add("sEvent", bugreport.Text);

			ASCIIEncoding encoding = new ASCIIEncoding();
			Dictionary<string, byte[]>[] rgFiles = null;
			if(listFiles.CheckedItems.Count > 0) {
				rgFiles = new Dictionary<string, byte[]>[listFiles.CheckedItems.Count];
				int i=0;
				foreach(ListViewItem lvi in listFiles.CheckedItems) {
					rgFiles[i] = new Dictionary<string, byte[]>();
					rgFiles[i]["name"] = encoding.GetBytes("File" + (i + 1).ToString());
					//rgFiles[i]["name"] = encoding.GetBytes(listFiles.Items[i].Text);
					//rgFiles[i]["filename"] = encoding.GetBytes(lvi.text.ToString().Substring(lvi.Tag.ToString().LastIndexOf("\\") + 1));
					rgFiles[i]["filename"] = encoding.GetBytes(lvi.Text);
					rgFiles[i]["contenttype"] = encoding.GetBytes(GetMIMEType(lvi.Tag.ToString()));
					FileStream fs = new FileStream(lvi.Tag.ToString(), FileMode.Open);
					BinaryReader br = new BinaryReader(fs);
					rgFiles[i]["data"] = br.ReadBytes((int)fs.Length);
					fs.Close();
					++i;
				}
				args.Add("nFileCount", listFiles.CheckedItems.Count.ToString());
			}

			if(correspondent.Text.Length > 0)
				args.Add("sCustomerEmail", correspondent.Text);
			FogBugzAPI fb = FogBugzAPI.Instance(false);
			fb.api.Cmd("new", args, rgFiles);
			Properties.Settings.Default.Save();*/
		}

	/*	private string getName(string s) {
			string ret = "";
			try {
				int index = s.IndexOf(':');
				ret = s.Substring(0, index);//s.Substring(s.IndexOf(" : ") + 3);
			}
			catch(System.Exception) { }
			return ret;
		}*/

		private void FillDropDown(APIResult result, ComboBox combo) {
			foreach(Tuple<string, string> res in result)
				combo.Items.Add(new ComboItem(res.Item1, res.Item2));

		}

/*		private void FillDropDownWithResults(XmlNodeList list, ComboBox combo, string sName, string ixName) {
			foreach(XmlNode node in list)
				combo.Items.Add(String.Format("{0} : {1}", node.SelectNodes(sName)[0].InnerText, node.SelectNodes(ixName)[0].InnerText));
			if(combo.Items.Count > 0)
				combo.SelectedIndex = 0;
		}*/

		private string GetSenderSMTPAddress(MailItem mail) {
			string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
			if(mail == null)
				throw new ArgumentNullException();
			if(mail.SenderEmailType == "EX") {
				AddressEntry sender = mail.Sender;
				if(sender != null) {
					if(sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) {
						ExchangeUser user = sender.GetExchangeUser(); //ExchangeUser.PrimarySmtpAddress should contain a proper external email
						if(user != null)
							return user.PrimarySmtpAddress;
						else
							return null;
					}
					else
						return sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string;
				}
				else
					return null;
			}
			else
				return mail.SenderEmailAddress;
		}

		private void listFiles_MouseMove(object sender, MouseEventArgs e) {
			Point ptCursor = Cursor.Position;
			ptCursor = listFiles.PointToClient(ptCursor);
			ListViewItem Item = listFiles.GetItemAt(ptCursor.X, ptCursor.Y);
			if(Item != null && Item == lastItem) {
				Point loc = Cursor.Position;
				loc.Y -= previewForm.Height + 5;
				loc.X += 5;
				previewForm.Location = loc;
			}
			else {
				if(Item != null) {
					string ext = Path.GetExtension(Item.Tag.ToString());
					if(ext.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase) || ext.Equals(".png", StringComparison.InvariantCultureIgnoreCase) ||
					ext.Equals(".gif", StringComparison.InvariantCultureIgnoreCase) || ext.Equals(".bmp", StringComparison.InvariantCultureIgnoreCase)) {
						previewForm.attachPreview.Load(Item.Tag.ToString());
						if(previewForm.attachPreview.Image.Width > 220 || previewForm.attachPreview.Image.Height > 160) {
							previewForm.attachPreview.SizeMode = PictureBoxSizeMode.StretchImage;
							previewForm.ClientSize = new System.Drawing.Size(220, 160);
						}
						else {
							previewForm.attachPreview.SizeMode = PictureBoxSizeMode.Normal;
							previewForm.ClientSize = new System.Drawing.Size(previewForm.attachPreview.Image.Width, previewForm.attachPreview.Image.Height);
						}
						Point loc = Cursor.Position;
						loc.Y -= previewForm.attachPreview.Height + 5;
						loc.X += 5;
						previewForm.Location = loc;
						previewForm.Show();
						lastItem = Item;
						return;
					}
				}
				lastItem = null;
				previewForm.attachPreview.Image = null;
				previewForm.Hide();
			}
		}

		private void listFiles_MouseLeave(object sender, EventArgs e) {
			lastItem = null;
			previewForm.attachPreview.Image = null;
			previewForm.Hide();
		}

		private void title_TextChanged(object sender, EventArgs e) {
			if(title.Text.Equals(NEW_TITLE))
				title.ForeColor = SystemColors.ControlDark;
			else
				title.ForeColor = SystemColors.WindowText;
		}

		private void title_Click(object sender, EventArgs e) {
			title.SelectAll();
		}

		private void project_SelectedIndexChanged(object sender, EventArgs e) {

		}
	}
#endif
}
